import { DependencyContainer, Response, useEntityManager } from "@sker/core"
import { KsAccount, KsLiveRoom, KsRedPacket } from "@sker/entities"
import { useData } from "@sker/runtime"
import dayjs from "dayjs"
import { z } from "zod"


export default async (injector: DependencyContainer) => {
    const res = injector.resolve(Response)
    const input = z.object({
        type: z.optional(z.string())
    })
    let start = dayjs().subtract(8, 'hour').hour()
    const body = input.parse(useData())
    body.type = body.type || '口令';
    const list = await useEntityManager(async m => {
        const list = await m.createQueryBuilder()
            .select('room.link', 'link')
            .addSelect('room.name', 'name')
            .addSelect('room.user_id', 'user_id')
            .addSelect('room.open_time', 'open_time')
            .addSelect(`account.ksid`, `ksid`)
            .from(KsLiveRoom, 'room')
            .leftJoin(KsRedPacket, 'red', 'red.room_id=room.id')
            .leftJoin(KsAccount, 'account', 'account.user_id=room.user_id')
            .where(`date_part('hour',room.open_time)>=:start and date_part('hour',room.open_time)<=:end`, { start, end: start+1 })
            .andWhere('red.type=:type', { type: body.type })
            .andWhere('account.update_date<=:update_date', { update_date: dayjs().subtract(30, 'minute').toDate() })
            .orderBy('random()')
            .limit(100)
            .execute()
        return list.map(item => {
            item.link = `https://live.kuaishou.com/u/${item.ksid}`
            item.share = `kwai://live/play/~${item.user_id}`
            return item;
        })
        // return list;
    })

    res.type('html')
    res.end(`<ul>${list.map(it=>`<li><a href="${it.share}">${it.name}</a></li>`)}</ul>`)
}